package com.cat.binaryTree;

import javax.management.relation.InvalidRelationTypeException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/reverse-odd-levels-of-binary-tree/description/
 * @create 2025/9/29 11:53
 * @since JDK17
 */

public class Solution88 {
    public TreeNode reverseOddLevels(TreeNode root) {
        Deque<TreeNode> cur = new ArrayDeque<>();
        cur.add(root);
        for (int i = 1; !cur.isEmpty(); i++) {
            List<TreeNode> list = new ArrayList<>();
            for (int j = 0, end = cur.size(); j < end; j++) {
                var node = cur.poll();
                if (i % 2 == 0) {
                    list.add(node);
                }
                if (node.left != null) {
                    cur.addLast(node.left);
                    cur.addLast(node.right);
                }
            }
            for (int l = 0, r = list.size() - 1; l < r; l++, r--) {
                int t = list.get(l).val;
                list.get(l).val = list.get(r).val;
                list.get(r).val = t;
            }
        }

        return root;
    }
}
